import React, { useContext, createContext, useState } from 'react'

// 初始化上线文
const MyContext = createContext()

const LoginTools = ({ children }) => {
  const [count, setCount] = useState(0)

  const increment = () => setCount(count + 1)
  const decrement = () => setCount(count - 1)
  const login = () => console.log('登录成功')
  const logout = () => console.log('退出登录成功')


  return (
    <>
      <span>计数:{count}</span>
      <MyContext.Provider value={{ count, setCount, increment, decrement, login, logout }} children={children} />
    </>
  )
}

export default function ContextDemo() {

  return (
    <>
      <h2>useContext的使用</h2>
      <LoginTools children={<Child />} />

    </>
  )
}

function Child() {
  /**  const { increment, decrement, login, logout } = useContext(MyContext)
  return (
    <>

      <button onClick={increment}>添加</button>
      <button onClick={decrement}>减法</button>
      <button onClick={login}>登录</button>
      <button onClick={logout}>退出登录</button>
    </>
  )
  */

  return (
    <>
      <button>hello</button>
      <MyContext.Consumer>

        {/* 生产者与消费者模式 */}
        {
          value => {
            const { increment, decrement, login, logout } = value
            return (
              <>
                <button onClick={increment}>添加</button>
                <button onClick={decrement}>减法</button>
                <button onClick={login}>登录</button>
                <button onClick={logout}>退出登录</button>
              </>
            )
          }
        }
      </MyContext.Consumer>
    </>
  )
}